<template>
  <div class="upload-file">
    <a-upload ref="fileUpload" :action="state.uploadFileUrl" :headers="state.headers" :show-upload-button="!props.onlyShow" :show-remove-button="!props.onlyShow"
      :file-list="state.fileList" :limit="props.limit" :show-file-list="true" :show-retry-button="false"
      @exceed-limit="handleExceed" @error="handleUploadError" @before-upload="handleBeforeUpload" @success="handleUploadSuccess" @before-remove="handleDelete">
    </a-upload>
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { Message } from '@arco-design/web-vue'
import {getToken} from "@/utils/auth";
import {reactive, ref, onMounted, defineProps, defineEmits, nextTick, computed} from "vue";

let props = defineProps({
  limit : {type : Number, default: 10},
  fileSize : {type : Number, default: 30},
  fileType : {type : Array, default: () => ["doc","docx","xls",'xlsx',"zip","rar","ppt","txt","pdf","log","ini","png","jpg","jpeg","mp3","mp4","avi","flv"]},
  isShowTip : {type : Boolean, default: true},
  onlyShow : {type : Boolean, default: false},
  entityId : {type : Number, default: 0},
  entityTypeId : {type : Number, default: 0},
})

const state = reactive({
  number: 0,
  uploadList: [],
  baseUrl: import.meta.env.VITE_API_BASE_URL,
  uploadFileUrl: import.meta.env.VITE_API_BASE_URL + "/common/upload", // 上传文件服务器地址
  headers: {
    ['X-Token'] : getToken(),
    entityTypeId: ''+props.entityTypeId,
    entityId: ''+props.entityId,
  },
  fileList: [],
})
const tips = computed( () =>{
  if(props.isShowTip && (props.fileType || props.fileSize)){
    return "大小不超过" + props.fileSize +"MB的文件，格式为" + props.fileType?.join("/") + "的文件"
  }else{
    return "";
  }
})

// 文件个数超出
const handleExceed = ()=>{
  Message.error(`上传文件数量不能超过 ${props.limit} 个!`)
}
// 上传失败
const handleUploadError = (fileItem)=>{
  Message.error("上传文件失败，请重试" )
}
// 上传前校检格式和大小
const handleBeforeUpload = (file)=>{
  if(props.fileType){
    const fileName = file.name.split('.');
    const fileExt = fileName[fileName.length - 1];
    const isTypeOk = props.fileType.indexOf(fileExt) >= 0;
    if (!isTypeOk) {
      Message.error(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  if(props.fileSize){
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      Message.error(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  state.number++;
  return true;
}
// 上传成功回调
const handleUploadSuccess = (fileItem)=>{
  const res = JSON.parse(fileItem.response)
  if (parseInt(res.code) === 200 && fileItem.status == 'done') {
    const {data} = res;
    state.uploadList.push({ name: fileItem.file.name, url: state.baseUrl + data.fileName, fId:data.fId});
    uploadedSuccessfully();
  }else{
    state.number--;
    Message.error(res.msg || '上传未知错误');
    uploadedSuccessfully();
  }
}
const uploadedSuccessfully = () => {
  if(state.number > 0 && state.uploadList.length === state.number){
    state.fileList = state.fileList.concat(state.uploadList);
    state.uploadList = [];
    state.number = 0;
  }
}
const handleDelete = (fileItem) => {
  return axios.post('/common/deletefile/' + fileItem.fId)
}
//初始化数据
const initFileList = () => {
  if(props.entityId > 0){
    axios.get('/common/listfile/' + props.entityTypeId + "/" + props.entityId).then( (res) => {
      const {data} = res
      if(data && Array.isArray(data)){
        data.forEach(f=>{
          state.fileList.push({name: f.fileName, url: state.baseUrl + f.filePath, fId : f.fId})
        })
      }
    })
  }
}
onMounted(()=>{
  initFileList();
})
</script>

<style scoped>

</style>
